import React, { useEffect, useState } from "react";
import Taro, { useRouter, useDidShow } from "@tarojs/taro";
import {
  View,
  Swiper,
  SwiperItem,
  Text,
  Image,
  Picker,
} from "@tarojs/components";
import onPay from "@/common/utils/pay";
import { GoodsItemData } from "@/components/GoodsItem/data";
import GoodsItem from "@/components/GoodsItem";
import yinzhangIcon from "@/images/icon_contract_left.png";
import rightIcon from "@/images/icon_right.jpg";
import phoneIcon from "@/images/phone_icon.png";
import IdIcon from "@/images/id_icon.png";
import { setData, getData } from "@/src/globalData";

import * as api from "./api";
import "./index.scss";
import { SkuItData } from "../goodsDetail/data";

const Index: React.FC<{}> = () => {
  const [goodsInfo, setGoodsInfo] = useState<GoodsItemData>({});
  const [count, setCount] = useState(0);
  const [cateInfo, setCateInfo] = useState<SkuItData>({});
  const [invoiceInfo, setInvoiceInfo] = useState<{ [key: string]: string }>({});
  const [posterId, setPosterID] = useState(null);
  const [paying, setPaying] = useState(false);
  const router = useRouter();

  useDidShow(() => {
    const newInvoiceInfo = getData("invokceData");
    if (newInvoiceInfo) {
      setInvoiceInfo(newInvoiceInfo);
    }
  });

  useEffect(() => {
    return () => {
      setData("invokceData", null);
    };
  }, []);

  useEffect(() => {
    if (router.params) {
      const params = JSON.parse(router.params.params);
      console.log(params);
      setCateInfo(params.cateInfo);
      setGoodsInfo(params.goodsInfo);
      setCount(params.count);
      params.poster_id && setPosterID(params.poster_id);
    }
  }, [router]);

  const goSignerForm = () => {
    Taro.navigateTo({
      url: "/pages/signerForm/index?params=" + JSON.stringify(invoiceInfo),
    });
  };

  const despatch_type_map: any = {
    logistics: "物流",
    phone_top_up: "手机充值",
    eduction_contract: "教育合同",
  };

  const onSubmit = async () => {
    if (goodsInfo.despatch_type === "eduction_contract") {
      if (!invoiceInfo.name) {
        Taro.showToast({
          title: "请完善合同人信息！",
          icon: "none",
        });
        return;
      }
      Taro.showLoading({ title: "", mask: true });
      try {
        let params: any = {
          order_info: JSON.stringify({
            strike_price: count * cateInfo.sale_price,
            invoice_info: invoiceInfo,
            deposit: goodsInfo.deposit,
            goods_list: [
              {
                quantity: count,
                specification_id: cateInfo.id,
              },
            ],
          }),
        };

        console.log("params--->>", params);
        console.log("goodInfo--->>", goodsInfo);

        if (posterId) {
          params.poster_id = posterId;
        }

        const { result, status } = await api[
          posterId ? "customer_order_posteradd" : "customer_order_add"
        ](params);

        if (status === "ok") {
          console.log("ok", result.order_id);
          await onPay(
            result.order_id,
            () => {
              Taro.navigateTo({
                url: `/pages/orderDetail/index?order_id=${result.order_id}`,
              });
            },
            () => {
              Taro.navigateTo({
                url: `/pages/orderDetail/index?order_id=${result.order_id}`,
              });
            }
          );
        } else {
          Taro.hideLoading();
        }
      } catch (err) {
        console.log("err--------->>>", err);
      } finally {
      }
    }
  };

  return (
    <View className="order-confirm-page">
      <View className="dispatch-info" onClick={goSignerForm}>
        <Image className="icon" src={yinzhangIcon} />
        {invoiceInfo.name ? (
          <View className="info">
            <View className="name">{invoiceInfo.name}</View>
            <View className="phone">
              <Text>{invoiceInfo.phone}</Text>
              <Image src={phoneIcon} mode="widthFix" />
            </View>
            <View className="identification">
              <Text>{invoiceInfo.identification}</Text>
              <Image src={IdIcon} mode="widthFix" />
            </View>
          </View>
        ) : (
          <View className="info">
            <View className="info-it">请填写合同人信息</View>
          </View>
        )}

        <Image className="right-icon" src={rightIcon} />
      </View>

      <View className="info-card">
        <View className="title">报考信息</View>
        <GoodsItem
          className="goods-item"
          id={goodsInfo.id}
          thumbnail={cateInfo.show_image}
          title={goodsInfo.title}
          school_name={goodsInfo.school_name}
          major_name={goodsInfo.major_name}
          duration={goodsInfo.duration}
          school_city={goodsInfo.school_city}
          production_name={goodsInfo.category || goodsInfo.production_name}
          brand_name={goodsInfo.brand_name}
          sale_price={cateInfo.original_price}
          agent_name={goodsInfo.agent_name}
          category={goodsInfo.category || goodsInfo.production_name}
          count={count}
        />
        <View className="info-it">
          <View className="label">属性</View>
          <View className="value">
            {cateInfo.specification_value_list &&
              cateInfo.specification_value_list.length && (
                <Text>
                  {cateInfo.specification_value_list.map((it, idx) => {
                    return `${it.attribute}${
                      idx < cateInfo.specification_value_list.length - 1
                        ? "/"
                        : ""
                    }`;
                  })}
                </Text>
              )}
          </View>
        </View>
        <View className="info-it">
          <View className="label">发货</View>
          <View className="value">
            {despatch_type_map[goodsInfo.despatch_type]}
          </View>
        </View>
      </View>

      <View className="info-card">
        <View className="title">金额</View>
        <View className="info-it">
          <View className="label">助学原价</View>
          <View className="value">
            ￥{(cateInfo.original_price / 100).toFixed(2)}
          </View>
        </View>
        <View className="info-it">
          <View className="label">优惠金额</View>
          <View className="value" style="color:#FF0000;">
            -￥
            {((cateInfo.original_price - cateInfo.sale_price) / 100).toFixed(2)}
          </View>
        </View>

        <View className="info-it">
          <View className="label">成交价：</View>
          <View className="value">
          ￥{((count * cateInfo.sale_price) / 100).toFixed(2)}
          </View>
        </View>
      </View>

      {goodsInfo.pay_services === "full_payment" && (
        <View className="info-card">
          <View className="info-it">
            <View className="label">支付方式</View>
            <View className="value">全款</View>
          </View>
          <View className="info-it">
            <View className="label">支付金额</View>
            <View className="value" style="color:#43C590;">
              {posterId ? (
                <Text>￥{(goodsInfo.deposit / 100).toFixed(2)}</Text>
              ) : (
                <Text>
                  ￥{((count * cateInfo.sale_price) / 100).toFixed(2)}
                </Text>
              )}
            </View>
          </View>
        </View>
      )}

      {/*分期付款的暂时一定是海报商品*/}
      {goodsInfo.pay_services === "installment" && (
        <View className="info-card">
          <View className="info-it">
            <View className="label">支付方式</View>
            <View className="value">分期付款</View>
          </View>
          <View className="info-it">
            <View className="label">支付金额</View>
            <View className="value" style="color:#43C590;">
              <Text>￥{(goodsInfo.deposit / 100).toFixed(2)}</Text>
            </View>
          </View>
          <View className="info-it">
            <View className="label">欠缴金额</View>
            <View className="value" style="color:#FE0000;">
              {(cateInfo.sale_price / 100).toFixed(2)}
            </View>
          </View>
        </View>
      )}

      <View className="blank"></View>

      {posterId ? (
        <View className="footer-content">
          <View className="l">
            <Text>需付款：</Text> ￥
            {((count * goodsInfo.deposit) / 100).toFixed(2)}
            <Text className="wait-pay">
              欠缴： {(cateInfo.sale_price / 100).toFixed(2)}
            </Text>
          </View>
          <View className="r">
            <View className="button" onClick={onSubmit}>
              立即支付
            </View>
          </View>
        </View>
      ) : (
        <View className="footer-content">
          <View className="l">
            <Text>需付款：</Text> ￥
            {((count * cateInfo.sale_price) / 100).toFixed(2)}
          </View>
          <View className="r">
            <View className="button" onClick={onSubmit}>
              立即支付
            </View>
          </View>
        </View>
      )}
    </View>
  );
};

export default Index;
